package com.avexVertex.controller;

import com.avexVertex.pojo.Result;
import com.avexVertex.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /**
     * 本地磁盘存储方案
     *
     * @param name
     * @param age
     * @param file
     * @return
     * @throws IOException
     */
    //@PostMapping("/upload")
    public Result upload(@RequestParam("name") String name,
                         @RequestParam("age") Integer age,
                         @RequestParam("file") MultipartFile file) throws IOException {
        log.info("接收到的参数:{},{},{}", name, age, file);

        //获取原始文件名
        String fileOriginalFilename = file.getOriginalFilename();

        //新的文件名
        String extension = fileOriginalFilename.substring(fileOriginalFilename.lastIndexOf('.'));
        String newFileName = UUID.randomUUID().toString() + extension;

        //保存文件
        file.transferTo(new File("F:/Desktop/破烂杂项/代码文件测试文件夹/" + newFileName));
        return Result.success();
    }


    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        log.info("文件上传：{}", file.getOriginalFilename());
        //将文件交给阿里云OSS存储
        String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
        log.info("文件上传OSS,url:{}", url);

        return Result.success(url);
    }

}
